"""
Filters used by Glittr to make the responses from Flickr more friendly.

"""

# module imports
from utility import from_timestamp, from_date, to_timestamp, to_date, to_ymd

# filters for outgoing parameters
OUTGOING_KEYS = {
    'date_posted':to_date,
    'date_taken':to_date,
    'min_upload_date':to_timestamp,
    'max_upload_date':to_timestamp,
    'min_date':to_timestamp,
    'min_taken_date':to_date,
    'max_taken_date':to_date,
    'date':to_ymd,
}

def params_filter(input):
    for k,v in input.iteritems():
        if k in OUTGOING_KEYS:
            if not isinstance(v, basestring):
                convert_f = OUTGOING_KEYS[k]
                input[k] = convert_f(v)
    return input

# items with these keys are converted to datetime objects, using the function
# set as the value for the key
INCOMING_TIME_KEYS = {
    'lastupdate':from_timestamp,
    'posted':from_timestamp,
    'dateuploaded':from_timestamp,
    'fromdate':from_timestamp,
    'todate':from_timestamp,
    'firstdate':from_timestamp,
    'firstdatetaken':from_date,
    'taken':from_date,
}

def dates_filter(input):
    if isinstance(input, dict):
        for k,v in input.iteritems():
            if k in INCOMING_TIME_KEYS:
                convert_f = INCOMING_TIME_KEYS[k]
                input[k] = convert_f(v)
            elif isinstance(v, dict) or isinstance(v, list):
                input[k] = dates_filter(v)
        return input

    elif isinstance(input, list):
        for k,v in enumerate(input):
            input[k] = dates_filter(v)
        return input

    else:
        return input

# there are some keys that are inconsistent between reponses from
# api calls and parameters to them
INCOMING_KEY_CONVERSIONS = {
    'isfriend': 'is_friend',
    'isfamily': 'is_family',
    'ispublic': 'is_public',
}

def keys_filter(input):
    if isinstance(input, dict):
        for k,v in input.iteritems():
            if k in INCOMING_KEY_CONVERSIONS:
                new_k = INCOMING_KEY_CONVERSIONS[k]
                input[new_k] = input[k]
                del input[k]
            elif isinstance(v, dict) or isinstance(v, list):
                input[k] = keys_filter(v)
        return input

    elif isinstance(input, list):
        for k,v in enumerate(input):
            input[k] = keys_filter(v)
        return input

    else:
        return input

